package com.wuming.house.controller;

import com.lyyzoo.fastdfs.client.FastDFSClient;
import com.wuming.house.core.HuiqianConstent;
import com.wuming.house.model.GoodImage;
import com.wuming.house.service.GoodImageService;
import com.wuming.house.util.DateUtil;
import com.yuanzhuo.common.core.mapper.BeanMapper;
import com.yuanzhuo.common.core.util.YzStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @author hanfei
 * @Title :BaseController
 * @ProjectName : drivermanage
 * @Description:
 * @date 18/6/26下午5:22
 */
@Controller
@RequestMapping("/web/base")
public class BaseController {
    protected static final int PAGE_SIZE = 5;

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    protected BeanMapper beanMapper = new BeanMapper();

    protected FastDFSClient fastDFSClient = new FastDFSClient();

    /**
     * 临时文件下载
     *
     * @param filename
     * @param request
     * @param response
     * @param showName
     * @throws IOException
     * @author zhangyu
     * @date 2016-8-9
     * @time 上午11:41:41
     */
    @RequestMapping("downLoadTempFile")
    protected void downLoadTempFile(@RequestParam String filename, HttpServletRequest request,
                                    HttpServletResponse response, @RequestParam String showName) throws IOException {
        File backFileName = new File(System.getProperty("java.io.tmpdir") + File.separator + filename);
        if (backFileName.exists()) {
            response.setHeader("Content-Disposition", "attachment; filename=\""
                    + YzStringUtils.toUtf8String(showName) + "\"");
            InputStream in;
            try {
                ServletOutputStream os = response.getOutputStream();
                in = new FileInputStream(backFileName);
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);// 将文件写入服务器
                }
                os.close();
                in.close();
                backFileName.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    protected String uploadImage(MultipartFile file, String name, Integer type) throws IOException {
        if (file != null) {// 判断上传的文件是否为空
            String path = null;// 文件路径
            String fileType = null;// 文件类型
            String fileName = file.getOriginalFilename();// 文件原名称
            logger.info("上传的文件原名称:{}", fileName);
            // 判断文件类型
            fileType = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
            String savePath = "";
            if (fileType != null) {// 判断文件类型是否为空
                if ("JPEG".equals(fileType.toUpperCase()) || "GIF".equals(fileType.toUpperCase()) || "PNG".equals(fileType.toUpperCase()) || "JPG".equals(fileType.toUpperCase())) {
                    String realPath = HuiqianConstent.IMGUPLOADDIR;
                    // 自定义的文件名称
                    String trueFileName = UUID.randomUUID().toString() + "." + fileType.toUpperCase();
                    // 设置存放图片文件的路径
                    path = realPath + File.separator + name + File.separator + DateUtil.dateToString(new Date(), "yyyyMMdd") + File.separator + type + File.separator;
                    File filePath = new File(path);
                    if (!filePath.exists()) {
                        filePath.mkdirs();
                    }
                    path = path + trueFileName;
                    savePath = "/" + name + "/" + DateUtil.dateToString(new Date(), "yyyyMMdd") + "/" + type + "/" + trueFileName;
                    file.transferTo(new File(path));
                }
            }
            logger.info("文件成功上传到指定目录下,文件目录:{},", path);
            return savePath;
        }
        return "";
    }

    protected String getImagePath(Integer imageId, GoodImageService goodImageService) {
        try {
            if (null != imageId) {
                GoodImage goodImage = goodImageService.getImageById(imageId);
                return goodImage.getImagePath();
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("数据库查询异常,异常信息:{}", e.getCause());
        }
    }
}
